package com.hc.appanimal;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hc.DTO.AnimalCategoryMasterDTO;
import com.hc.DTO.AnimalDTO;
import com.hc.DTO.AnimalImagesDTO;
import com.hc.DTO.TokenDTO;
import com.hc.constants.Constants;
import com.hc.model.utils.AnimalCategoryMasterModel;
import com.hc.model.utils.AnimalImagesModel;
import com.hc.model.utils.AnimalModel;
import com.hc.model.utils.TokenModel;

import android.R.integer;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Environment;

public class AsystaskUpdateCategory extends AsyncTask<Void, Void, Void> {

	Context mContext;
	Dialog dialog;
	AnimationDrawable frameAnimation;
	TokenDTO token;

	public AsystaskUpdateCategory(Context context, TokenDTO _token) {
	
		String path = Constants.URL_CATEGORY;
		String[] strs = path.split("/");
		File file = new File(Environment.getExternalStorageDirectory() + "/"
				+ Constants.APP_NAME + "/" + strs[4] + "/");
//		deleteDirectory(file);
		deleteDir(file);
		mContext = context;
		token = _token;
		dialog = new Dialog(mContext, R.style.NewDialog);
		dialog.setContentView(R.layout.loading);

		dialog.setCancelable(false);
		dialog.findViewById(R.id.loading_icon).setBackgroundResource(
				R.drawable.spin_animation);
		frameAnimation = (AnimationDrawable) dialog.findViewById(
				R.id.loading_icon).getBackground();
		dialog.show();
		frameAnimation.start();
	}

	@Override
	protected Void doInBackground(Void... params) {
		
		AnimalCategoryMasterModel model = AnimalCategoryMasterModel
				.getInstance();
		model.deleteAnimal(mContext);
		HttpEntity httpEntity = null;
		HttpClient client = new DefaultHttpClient();
		HttpGet method = new HttpGet(Constants.URL_GET_CATEGORY);
		method.setHeader("Content-Type",
				"application/x-www-form-urlencoded;charset=UTF-8");
		method.setHeader("Authorization",
				token.getToken_type() + " " + token.getAccess_token());
		try {
			HttpResponse response = client.execute(method);
			httpEntity = response.getEntity();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					(response.getEntity().getContent())));
			String output;
			System.out.println("Output from Server .... \n");
			StringBuilder builder = new StringBuilder();
			while ((output = br.readLine()) != null) {
				System.out.println(output);
				builder.append(output);
			}
			
			String strJson = builder.toString();
			if (strJson != null) {
				JSONArray jsonArr = new JSONArray(strJson);
				for (int i = 0; i < jsonArr.length(); i++) {
					JSONObject obj = jsonArr.getJSONObject(i);

					int Id = obj.getInt("Id");
					String AnimalCategory = obj.getString("AnimalCategory");
					int OrderNo = obj.getInt("OrderNo");
					String UpdatedOn = obj.getString("UpdatedOn");

					AnimalCategoryMasterDTO categoryDTO = new AnimalCategoryMasterDTO();
					categoryDTO.setId(Id);
					categoryDTO.setAnimalCategory(AnimalCategory);
					categoryDTO.setOrderNo(OrderNo);
					categoryDTO.setUrlImages(Constants.URL_CATEGORY
							+ AnimalCategory + ".png");

					AnimalCategoryMasterModel modelCategory = AnimalCategoryMasterModel
							.getInstance();
					boolean flagCategory = modelCategory.getIdCategory(
							mContext, Id);
					if (!flagCategory) {
						modelCategory.insertCategory(categoryDTO, mContext);
					} else {
						modelCategory.updateCategory(categoryDTO, mContext);
					}

				}
				
//				ArrayList<Integer> ids = new ArrayList<Integer>();
//				for (AnimalCategoryMasterDTO dtonew : arrData) {
//					ids.add(dtonew.getId());
//				}
//				ArrayList<Integer> idss = new ArrayList<Integer>();
//				for (AnimalCategoryMasterDTO dtoold : arr) {
//					idss.add(dtoold.getId());
//				}
//				for (int i = 0; i < idss.size(); i++) {
//					if (ids.get(i) != idss.get(i)) {
//						
//					}
//				}
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	private void recursiveDelete(File fileOrDirectory) {
        if (fileOrDirectory.isDirectory())
            for (File child : fileOrDirectory.listFiles())
                recursiveDelete(child);

        fileOrDirectory.delete();
    }
	public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                   // return false;
                }
            }
        }

        // The directory is now empty so delete it
        return dir.delete();
    }

	@Override
	protected void onPostExecute(Void result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		dialog.dismiss();
		frameAnimation.stop();
		new AsystaskDeleteAnimal(mContext, token).execute();
	}

}
